<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }}条</span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning" size="small" @click="$router.push('/import')">excel导入</el-button>
          <el-button v-allow="'export_excel'" type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            size="small"
            @click.native="showDialog=true
            "
          >新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table ref="employeesRef" border :data="list" :default-sort="{prop: 'timeOfEntry', order: 'ascending'}">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像" prop="staffPhoto">
            <template #default="{row}">
              <img :src="row.staffPhoto" alt="" style="width:100%">
            </template>
          </el-table-column>
          <el-table-column sortable label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment">
            <template #default="{row}">
              {{ EmployeesEnumFormat (row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column sortable label="入职时间" prop="timeOfEntry" />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" fixed="right" width="280">
            <template v-slot="{row}">
              <!-- 查询参数 -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <!-- 路径参数,需要路由进行接收 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssignRole(row.id)">分配角色</el-button>
              <el-button v-allow="'delete'" type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 3, 5, 10,20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工的弹层 start -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hResetForm">
        <addEmpDialog ref="addEmpRef" @close="showDialog=false" @success="hSuccess" />
      </el-dialog>
      <!-- 新建员工的弹层个end -->
      <!-- 给员工分配角色的弹层start -->
      <el-dialog title="分配角色" :visible.sync="roleShowDialog">
        <AssignRole
          v-if="roleShowDialog"
          :id="curId"
          @close="roleShowDialog =false"
          @success="hSaveAssignRoles"
        />
      </el-dialog>
    </div>
  </div>
</template>

<script>
import AssignRole from './assignRole'
import addEmpDialog from './empDialog.vue'
import { getEmployee, delEmployee } from '@/api/employees'
import EmployeesEnum from '@/constant/employees'
console.log('EmployeesEnum', EmployeesEnum)

// const hireType = {}
// EmployeesEnum.hireType.filter(item => {
//   hireType[item.id] = item.value
// })
const hireType = EmployeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  name: 'EleMing',
  components: {
    addEmpDialog, AssignRole
  },
  data() {
    return {
      // 分配角色的弹层
      roleShowDialog: false,
      // 页码值 , 默认第一页
      page: 1,
      // 每页显示的条数
      size: 10,
      // 保存员工的数据
      list: [],
      // 保存员工的总条数
      total: 0,
      showDialog: false,
      // 保存员工的ID
      curId: ''
    }
  },
  created() {
    this.loadEmployee()
  },
  methods: {
    hSaveAssignRoles() {
      this.roleShowDialog = false
    },
    // 用户点击分配角色
    hAssignRole(id) {
      this.roleShowDialog = true
      this.curId = id
    },
    formatForm(list) {
    // 1. 根据数据对象的键根据映射关系,得到一个中文的键, 放到一个数组中 ---header ['编号','密码']
    // 2.将每一个对象的值,存到一个数组中,所有的结果放入到一个打的数组中 -- data [["2018-11-30","总裁办"]]
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      const one = list[0]
      // 如果list中有数据 , 才需要生成表头
      if (!one) return // 没有数据 直接终止
      const header = Object.keys(one).map(enkey => {
        return map[enkey]
      })
      // 生成data数据
      const data = list.map(item => {
        const key = item.formOfEmployment
        // hireType = (1:"正式" , 2:"非正式")
        item['formOfEmployment'] = hireType[key] || '未知'
        return Object.values(item)
      })
      return { header: header, data: data }
    },
    async handleDownload() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log('res.data.rows', res.data.rows)
        const { header, data } = this.formatForm(res.data.rows)
        import('@/vendor/Export2Excel').then(excel => {
          // excel 指的是模块对象, 可以使用excel调用Export2Excel文件中的函数
          excel.export_json_to_excel({
            header: header,
            data: data,
            // 文件名
            filename: this.filename,
            // 文件适配宽度
            autoWidth: this.autoWidth,
            // 文件类型
            bookType: this.bookType
          })
          this.downloadLoading = false
        })
      } catch (error) {
        console.log(error)
      }
      this.downloadLoading = true
      //  import('@/vendor/Export2Excel') 懒加载的方式导入一个模块(文件)
    },
    hDel(id) {
      this.$confirm('确认删除吗？').then(async() => {
        const res = await delEmployee(id)
        console.log('delEmployee', res)
        // 判断页码值是否只有1
        if (this.list.length === 1) {
          this.page--
          // page的最小是必须是1
          if (this.page <= 0) {
            this.page = 1
          }
        }
        this.loadEmployee()
      }).catch((error) => {
        console.log(error)
      })
    },
    hResetForm() {
      this.$refs.addEmpRef.resetForm()
    },
    hSuccess() {
      // 计算 出最大的页码值
      this.total++
      const mixPage = Math.ceil(this.total / this.size)
      // 重新渲染数据
      this.page = mixPage
      this.loadEmployee()
      // 关闭弹层
      this.showDialog = false
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployee()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployee()
    },
    // 格式化聘用形式的函数
    EmployeesEnumFormat(data) {
      return hireType[data] || '未知元素'
    },
    async loadEmployee() {
      try {
        const res = await getEmployee(this.page, this.size)
        console.log('res.data', res.data)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }

  }
}
</script>
